#include "SimpleSequenceReader.h"

#include <unistd.h>
#include <iostream>
#include "Topic.h"
#include "recovery/fs/file/File.h"
#include "recovery/fs/file/FileRandomReader.h"

using recovery::Status;
using recovery::fs::file::File;
using recovery::fs::file::FileRandomReader;

SimpleSequenceReader::SimpleSequenceReader(Topic & topic)
: _topic(topic)
{
}
SimpleSequenceReader::~SimpleSequenceReader(){
}
// =0 -> OK; wait ok
// >0 -> available; 
// <0 -> error
int SimpleSequenceReader::polling(size_t ms){
	size_t sz;
	if(_reader->file().size(sz)){
		if(_readBytes < sz){//there are unread data 
			return sz - _readBytes;
		}
		// no data to be read , then sleep for a while
		std::cout << "usleep for a while" << std::endl;
		::usleep(ms * 1000);
		return 0;
	} 
	std::cerr << "get size failed" << std::endl;
	return -1;
}
Status SimpleSequenceReader::read(unsigned char * buf, const size_t size, size_t & readBytes){
	auto s = _reader->read(reinterpret_cast<char*>(buf), size, readBytes);
	if(s){
		_readBytes += readBytes;
		return Status::OK();
	}
	return s.toStatus();
}
bool SimpleSequenceReader::open(){
	_topic.open();
	File f(_topic.logPath());
	if(f.exist()){
		return FileRandomReader::openExist(_topic.logPath(), _reader).isOK();
	}
	return false;
}
bool SimpleSequenceReader::close(){
	_reader->close();
	_topic.close();
	return true;
}
